﻿using EntityClassMaker.Mods;
using log4net;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EntityClassMaker.DataBaseServer
{
    /// <summary>
    /// 访问数据库层
    /// </summary>
    public class CallSqlServer
    {
        private static CallSqlServer callSqlServer = new CallSqlServer();

        private CallSqlServer() { }

        public static CallSqlServer GetCallSqlServer() { return callSqlServer; }

        /* 
         * 一.列出本地所有数据库,或能根据指定路径获取本地数据库
         * 
         * 二.对指定数据库进行访问,能够进行读取字段,和备注等操作.
         * 
         * 
         */

        public ILog log { get; set; } = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        #region[    函数根据传入字段读取注册表判断是否存在    ]
        /// <summary>
        /// 函数根据传入字段读取注册表判断是否存在
        /// </summary>
        /// <param name="Database">程序名称</param>
        /// <returns>true说明存在,false不存在</returns>
        private Dictionary<string, bool> SeekLocalDatabase(string[] Database)
        {
            try
            {
                Dictionary<string, bool> IsExistExe = new Dictionary<string, bool>();
                for (int i = 0; i < Database.Length; i++)
                {
                    string softName = Database[i];
                    string strKeyName = string.Empty;
                    string softPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
                    RegistryKey regKey = Registry.LocalMachine;
                    RegistryKey regSubKey = regKey.OpenSubKey(softPath + softName + ".exe", false);

                    object objResult = regSubKey.GetValue(strKeyName);
                    RegistryValueKind regValueKind = regSubKey.GetValueKind(strKeyName);
                    if (regValueKind == Microsoft.Win32.RegistryValueKind.String)
                    {
                        IsExistExe.Add(Database[i], true);
                    }
                    else
                    {
                        IsExistExe.Add(Database[i], false);
                    }
                }
                return IsExistExe;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("CallSqlServer类下[SeekLocalDatabase | 函数根据传入字段读取注册表判断是否存在],发生错误,错误信息为:{0}", ex.Message);
                return null;
            }
        }
        #endregion

        /// <summary>
        /// 尝试连接制定的数据库
        /// </summary>
        /// <param name="ConnectDatabase">连接数据库需要的值{URL:连接地址,LoginName:登陆名,LoginPassword:登陆密码</param>
        /// <returns></returns>
        private bool TryToConnectDatabase(Dictionary<string, string> ConnectDatabase)
        {
            return false;
        }

        /// <summary>
        /// 获取有数据库名称
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllDbName(string DBName, string SQL, bool isLockHost = false)
        {
            List<string> dbNameList = new List<string>();
            try
            {
                DataTable dbNameTable = new DataTable();
                SqlConnection conn = getSqlConnection(DBName);
                SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
                lock (adapter)
                {
                    adapter.Fill(dbNameTable);
                }
                foreach (DataRow row in dbNameTable.Rows)
                {
                    dbNameList.Add(row["name"].ToString());
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                log.ErrorFormat("CallSqlServer类下[GetAllDbName | 获取有数据库名称],发生错误,错误信息为:{0}", ex.Message);
            }
            return dbNameList;

        }

        /// <summary>
        /// 取所有数据库名称
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> GetAllDbNameType(string DBName, string SQL)
        {
            Dictionary<string, string> dbNameList = new Dictionary<string, string>();
            DataTable dbNameTable = new DataTable();
            SqlConnection conn = getSqlConnection(DBName);
            SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
            lock (adapter)
            {
                adapter.Fill(dbNameTable);
            }
            foreach (DataRow row in dbNameTable.Rows)
            {
                if (row["Type"].ToString().Equals("sysname")) continue;
                dbNameList.Add(row["name"].ToString(), row["Type"].ToString());
            }
            conn.Close();
            return dbNameList;
        }


        /// <summary>
        /// 获取数据库连接对象
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public SqlConnection getSqlConnection(string dbName)
        {
            SqlConnection conn = new SqlConnection();
            try
            {
                conn.ConnectionString = string.Format("server=114.116.99.96;database={0};uid=think;pwd=123456;Enlist=true", dbName);
                conn.Open();
                return conn;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("CallSqlServer类下[getSqlConnection | 获取数据库连接对象],发生错误,错误信息为:{0}", ex.Message);
                return conn;
            }
        }
    }

    public class Field
    {
        public string Name { get; set; }
        public string Type { get; set; }
    }
}


